from datetime import datetime

from django import template


def my_capfirst(value):
    return value.capitalize()


register = template.Library()
register.filter('my_capfirst', my_capfirst)


@register.filter('time_since')
def time_since(value):
    now = datetime.now()
    timestamp = (now - value).total_seconds()
    if timestamp < 60:
        return "刚刚"
    elif 60 < timestamp < 60 * 60:
        res = int(timestamp / 60)
        return f'{res}小时前'
    elif 60 * 60 < timestamp < 60 * 60 * 24:
        res = int(timestamp / (60 * 60))
        return f'{res}小时前'
    elif 60 * 60 * 24 < timestamp < 60 * 60 * 24 * 30:
        res = int(timestamp / (60 * 60 * 24))
        return f'{res}天前'
    else:
        return value.strftime('%Y-%m-%d %H:%M:%S')


@register.simple_tag()
def current_time(format_string):
    return datetime.now().strftime(format_string)
